package com.masonluo.mlonlinejudge.utils;

import com.masonluo.mlonlinejudge.exceptions.DecompressionException;
import net.lingala.zip4j.ZipFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author masonluo
 * @date 2021/1/25 4:33 下午
 */
public class ZipUtils {

    public static void unzip(String zipFilePath) {
        unzip(zipFilePath, getParentPath(zipFilePath));
    }

    public static void unzip(String zipFilePath, String targetDir) {
        try {
            ZipFile zipFile = new ZipFile(zipFilePath);
            zipFile.extractAll(targetDir);
        } catch (IOException e) {
            throw new DecompressionException("Can't decompress the file [" + zipFilePath + "], it's not a legal zip file");
        }
    }

    /**
     * 去除后缀
     */
    public static String removeSuffix(String name) {
        int idx = name.lastIndexOf(".");
        if (idx > 0) {
            return name.substring(0, idx);
        }
        return name;
    }

    /**
     * 获取父目录的路径
     */
    public static String getParentPath(String path) {
        int idx = path.lastIndexOf("/");
        // 已经是根目录了
        if (idx == 0) {
            return "/";
        }
        return path.substring(0, idx);
    }
    /**
     * 压缩多个文件，压缩后的所有文件在同一目录下
     *
     * @param zipFileName 压缩后的文件名
     * @param files       需要压缩的文件列表
     * @throws IOException IO异常
     */
    public static void zipMultipleFiles(String zipFileName, File... files) throws IOException {
        ZipOutputStream zipOutputStream = null;
        try {
            // 输出流
            zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
            // 遍历每一个文件，进行输出
            for (File file : files) {
                zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
                FileInputStream fileInputStream = new FileInputStream(file);
                int readLen;
                byte[] buffer = new byte[1024];
                while ((readLen = fileInputStream.read(buffer)) != -1) {
                    zipOutputStream.write(buffer, 0, readLen);
                }
                // 关闭流
                fileInputStream.close();
                zipOutputStream.closeEntry();
            }
        } finally {
            if (null != zipOutputStream) {
                try {
                    zipOutputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        unzip("/Users/belle/Desktop/ZipDir/hello-world.zip", "/Users/belle/Desktop/ZipDir/Hello");
    }
}
